<template>
  <memberSelect @buy-member-ship="handleBuyMemberShip">
    <template #left>
      <TabsAside
        v-loading="categoryLoading"
        @active-tab-index="onActiveMenu"
        :tabs-list="categoryList"
      />
    </template>
    <template #content>
      <GoodsList :list="spuList" @handle-buy="onHandleBuy" @load="onHandleLoad">
        <template #tool>
          <ContentWrap class="!w-full border-none! mb-0!" :body-style="{ padding: 0 }">
            <el-row class="!w-full m-x-0!" justify="space-between" :gutter="5">
              <el-col :xs="24" :sm="24" :md="12" :lg="18" :xl="20">
                <Search
                  class="mb-10px"
                  placeholder-text="请输入商品名称\商品名称首字母\商品编码\条形码"
                  @emit-keywords="onHandleSearch"
                />
              </el-col>
              <el-col :xs="24" :sm="24" :md="12" :lg="6" :xl="4">
                <el-button type="primary" class="!w-100% mb-10px" @click="handleGoShoppingCart">
                  <Icon icon="meton:dailiyaoqing" :size="18" class="mr-5px" />
                  <Icon icon="ep:shopping-cart" :size="18" class="mr-5px" /> 购物车
                  {{ cartNumber }}
                </el-button>
              </el-col>
            </el-row>
          </ContentWrap>
        </template>
      </GoodsList>
    </template>
  </memberSelect>

  <SelectSku ref="SelectSkuRef" @add-cart="onAddCart" @buy="onBuy" />
  <!-- 付费会员商品弹框 -->
  <PaidMemberGoodsDialog ref="paidMemberGoodsDialogRef" />
</template>
<script lang="ts" setup>
defineOptions({ name: 'ShopSales' })
import { handleTree } from '@/utils/tree'
import TabsAside from '@/views/shop/components/tabsAside/index.vue' //商品分类列表
import GoodsList from './components/GoodsList.vue' //商品列表
import Search from '@/views/shop/components/search/index.vue' //搜索组件
import SelectSku from '@/views/shop/sales/components/SelectSku.vue' //选择sku
import PaidMemberGoodsDialog from '@/views/shop/sales/components/PaidMemberGoodsDialog.vue' //购物车赠送商品
import memberSelect from '../components/member/user/memberSelect.vue' //会员选择
import { appendSettlementProduct } from '../hooks/useGoods'
import * as ProductSpuApi from '@/api/shop/product/spu'
import * as OrderApi from '@/api/shop/trade/order'
const message = useMessage() // 消息弹窗
/** 付费会员购买 */
const paidMemberGoodsDialogRef = ref()
const handleBuyMemberShip = () => {
  paidMemberGoodsDialogRef.value.open()
  console.log('buyMemberShip')
}

/** 门店会员信息 */
import { useShopUserStoreWithOut } from '@/store/modules/shop/user'
const shopUserStore = useShopUserStoreWithOut()

const isSetUser = computed(() => {
  return shopUserStore.getIsSetUser
})
const shopUser = computed(() => {
  return shopUserStore.getUser
})

/** 购物车信息 */
import { useShopCartStoreWithOut } from '@/store/modules/shop/cart'
const shopCartStore = useShopCartStoreWithOut()
const cartNumber = computed(() => {
  return shopCartStore.getCartNumber
}) //购物车数量
const cartList = computed(() => {
  return shopCartStore.getCartList
})
/**
 * 商品分类菜单
 */
import * as ProductCategoryApi from '@/api/shop/product/category'
import _ from 'lodash'
const categoryLoading = ref(true) // 列表的加载中
const categoryList = ref<any[]>([]) // 列表的数据/** 查询列表 */
const getCategoryList = async () => {
  categoryLoading.value = true
  try {
    const data = await ProductCategoryApi.getCategoryList()
    categoryList.value = handleTree(data, 'id', 'parentId')
  } finally {
    categoryLoading.value = false
  }
}
// 选中菜单
const activeMenu = ref(0)
const onActiveMenu = (index: number) => {
  activeMenu.value = index
  spuList.value = []
  spuQueryParams.value.pageNo = 1
  getSpuList()
}

/**
 * 商品列表
 */
const spuQueryParams = ref({
  pageNo: 1,
  pageSize: 18,
  categoryId: undefined,
  keyword: undefined,
  userId: computed(() => {
    return shopUser.value.id
  })
}) // 查询参数 (给组件传值)
const spuLoading = ref(true)
const spuList = ref<any>([])
const spuTotal = ref(0)
const loadStatus = ref('') //列表数据状态

/** 查询列表 */
const getSpuList = async () => {
  if (!isSetUser.value) {
    // message.error('请先选择会员')
    return
  }
  spuLoading.value = true
  try {
    let unCategoryList = unref(categoryList.value)
    let unActiveMenu = unref(activeMenu.value)
    spuQueryParams.value.categoryId = unCategoryList[unActiveMenu].id
    const data = await ProductSpuApi.getSpuPage(spuQueryParams.value)
    if (data.list.length == 0) {
      return
    }
    if (shopUser.value.id > 0) {
      // 拼接结算信息（营销）
      const spuIds = data.list.map((item) => item.spuId).join(',')
      try {
        const settlementInfos = await OrderApi.getSettlementProduct({
          spuIds: spuIds,
          userId: shopUser.value.id
        })

        appendSettlementProduct(data.list, settlementInfos)
      } catch (error) {}
    }
    spuList.value = _.concat(spuList.value, data.list)
    spuTotal.value = data.total
    loadStatus.value = spuList.value.length < spuTotal.value ? 'more' : 'noMore'
  } finally {
    spuLoading.value = false
  }
}
/** 分页查询列表 */
const onHandleLoad = () => {
  if (loadStatus.value === 'noMore') {
    return
  }
  spuQueryParams.value.pageNo++
  getSpuList()
}
// 选择商品
const SelectSkuRef = ref()
const onHandleBuy = (item) => {
  if (!isSetUser.value) {
    message.error('请先选择会员')

    return
  }
  SelectSkuRef.value.open(item.spuId)
}
/**去购物车列表 */
const router = useRouter() // 路由对象
const handleGoShoppingCart = () => {
  let items = [] as EmptyArrayType
  cartList.value.map((item) => {
    items.push({
      skuId: item.sku.skuId,
      count: item.count,
      cartId: item.id,
      categoryId: item.spu.categoryId
    })
  })

  if (cartNumber.value > 0) {
    router.push({
      name: 'ShopPayCashier',
      query: {
        returnUrl: encodeURIComponent('/shop/sales')
      }
    })
  } else {
    message.error('请先选择商品')
  }
} //去购物车
const onAddCart = (e) => {
  if (!e.skuId) {
    message.error('请选择商品规格')
    return
  }
  shopCartStore.addCart(e)
} //加入购物车
const onBuy = (e) => {
  if (!e.skuId) {
    message.error('请选择商品规格')
    return
  }
} //立即购买
const onHandleSearch = (keyword) => {
  console.log(keyword)
  spuQueryParams.value.keyword = keyword
  spuList.value = []
  getSpuList()
}
// 监听会员变化
watch(
  () => shopUser.value.id,
  () => {
    shopCartStore.restSalesStateData()
    spuList.value = []
    if (shopUser.value.id > 0) {
      getSpuList()
      shopCartStore.getList() //获取购物车列表
    }
  }
)
onMounted(async () => {
  await getCategoryList()
  shopCartStore.getList() //获取购物车列表
  onActiveMenu(0)
})
</script>
